from django.shortcuts import render,redirect
from django.http import JsonResponse
import psutil,re,os,uuid
from django.db.models import F
import socket, platform
from django.views.decorators.csrf import csrf_exempt
from pathlib import Path
import json, datetime,time
from CMDB.settings import websshinfo
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from utils.cobbler import CobblerApi
from utils.remote_exec_cmd import remote_exec

from devops import models

def login_view(request):
    """
    登录
    :param request: username,password
    :return:
    """
    error_msg = "请登录"
    error_msg1 = "用户名或密码错误,或者被禁用,请重试"

    if request.method == "GET":
        return render(request, 'login.html', {'error_msg': error_msg, })

    if request.method == "POST":
        u = request.POST.get("username")
        p = request.POST.get("password")
        user = authenticate(request, username=u, password=p)
        if user is not None:
            if user.is_active:
                login(request, user)
                request.session['is_login'] = True
                login_ip = request.META['REMOTE_ADDR']
                models.LoginLogs.objects.create(user=request.user, ip=login_ip)
                return redirect('/ui')
            else:
                return render(request, 'login.html',
                              {'error_msg': error_msg1, })
        else:
            return render(request, 'login.html',
                          {'error_msg': error_msg1, })


'''
登出操作
'''


def logout(request):
    """
    退出
    :param request:
    :return:
    """
    request.session.clear()
    return redirect('login')

def default(request):
    return redirect('index')



# Create your views here.

def totime(timeStamp):
    timeArray = time.localtime(timeStamp)
    otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
    return otherStyleTime


def spendtime(starttime,endtime):
    d1 = datetime.datetime.strptime(starttime, "%Y-%m-%d %H:%M:%S")
    d2 = datetime.datetime.strptime(endtime, "%Y-%m-%d %H:%M:%S")
    datas = d2 - d1
    sec = datas.seconds
    if sec < 60:
        infos = "{} 秒".format(sec)
    elif sec < 3600:
        infos = ":".join(datas.__str__().split(":")[1:3])
    else:
        infos = datas

    return str(infos)

def val_to(dt):
    new_dt = {}
    for k, v in dt.items():
        if isinstance(v, datetime.datetime):
            v = v.strftime("%Y-%m-%d %H:%M:%S")

        if isinstance(v, bool):
            if v:
                v = 1
            else:
                v = 0
        new_dt[k] = v
        if isinstance(v, bool):
            v = u'是' if v else u'否'
        new_dt[k] = v

    return new_dt

@login_required
def index(request):
    return render(request, 'index.html')
    # return HttpResponse("success")

@login_required
def welcome(request):


    hostinfos = {}
    try:
        hostinfos["hostname"] = socket.gethostname()
    except Exception as e:
        hostinfos["hostname"] = str(e)

    iplists = []
    iflists = psutil.net_if_addrs()
    for nets in iflists:
        ip = str(iflists[nets][1][1])
        if ':' not in ip and '169.254' not in ip:
            iplists.append({nets: ip})

    hostinfos["ips"] = iplists
    hostinfos["pids"] = len(psutil.pids())
    hostinfos["cpus"] = psutil.cpu_count()
    diskset = psutil.disk_usage('/')
    memset = psutil.virtual_memory()
    hostinfos["disk"] = {}
    hostinfos["disk"]["total"] = int(diskset[0] / 1024.0 / 1024.0 / 1024.0)
    hostinfos["disk"]["free"] = int(diskset[2] / 1024.0 / 1024.0 / 1024.0)
    hostinfos["disk"]["useds"] = int(diskset[3])
    hostinfos["mem"] = {}
    hostinfos["mem"]["total"] = int(memset[0] / 1024.0 / 1024.0)
    hostinfos["mem"]["free"] = int(memset[4] / 1024.0 / 1024.0)
    hostinfos["mem"]["useds"] = int(memset[2])
    hostinfos["uptime"] = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
    hostinfos["system"] = platform.system() + " " + platform.version()
    print(hostinfos)

    hostinfos["assetcount"]=models.AssetInfo.objects.values('id').all().count()
    hostinfos["assetgroupcount"] = models.assetgroup.objects.values('id').all().count()

    return render(request, 'welcome.html',{"hostinfos":hostinfos})

@login_required
def webshell(request):
    id = request.GET
    print(id.get('id'))
    hostname=models.AssetInfo.objects.filter(id=id.get('id')).values("hostname").first()
    return render(request, 'assets/webshell.html', {'assetsid': id.get('id'), "webssh": websshinfo, "hostname":hostname})

@login_required
def asset_group(request):
    return render(request, 'asset-group/group.html')

@login_required
def scripts_group(request):
    return render(request, 'scripts/scripts-group.html')

@login_required
def asset_group_add(request):
    return render(request, 'asset-group/asset-group-add.html')

@login_required
def scripts_group_add(request):
    return render(request, 'scripts/scripts-group-add.html')

@login_required
def user_add(request):
    return render(request, 'users/user-add.html')

@login_required
def scripts_add(request):

    scriptgrouplists = models.ScriptsGroup.objects.all().values('id', 'groupname', 'path')
    scriptGroupL = []
    for scrobj in scriptgrouplists:
        scriptGroupL.append(val_to(scrobj))

    print(scriptGroupL)

    return render(request, 'scripts/scripts-add.html',{"scriptGroupL": scriptGroupL,})


@login_required
def user_edit(request):
    id = request.GET
    print(id.get('id'))
    # infos = models.AssetLoginUser.objects.filter(id=id.get('id')).values().first()
    # print(val_to(infos))
    return render(request, 'users/user-edit.html', {'userid': id.get('id')})

@login_required
def scripts_edit(request):
    id = request.GET
    print(id.get('id'))
    scriptgrouplists = models.ScriptsGroup.objects.all().values('id', 'groupname', 'path')
    scriptGroupL = []
    for scrobj in scriptgrouplists:
        scriptGroupL.append(val_to(scrobj))

    print(scriptGroupL)
    # infos=models.Scripts.objects.filter(id=id.get('id')).values().first()
    return render(request, 'scripts/scripts-edit.html', {'scriptsid': id.get('id'),"scriptGroupL":scriptGroupL})

@login_required
def assets_edit(request):
    id = request.GET
    print(id.get('id'))

    assetgrouplists = models.assetgroup.objects.all().values('id', 'groupname')
    loginusers = models.AssetLoginUser.objects.filter(status=0).all().values('id', 'username', 'status')
    scriptlists = models.Scripts.objects.all().values('id', 'zwname', 'qpname')
    hostypelists = models.HostType.objects.all().values('id', 'name', 'type')

    assetgroupL = []
    userinfL = []
    scriptL = []
    hosttypeL = []
    for chobj in assetgrouplists:
        assetgroupL.append(val_to(chobj))

    for usrobj in loginusers:
        userinfL.append(val_to(usrobj))

    for scrobj in scriptlists:
        scriptL.append(val_to(scrobj))

    for hosttypeobj in hostypelists:
        hosttypeL.append(val_to(hosttypeobj))

    # print(assetgroupL)
    # print(userinfL)

    # infos=models.Scripts.objects.filter(id=id.get('id')).values().first()
    return render(request, 'assets/edit-assets.html',
                  {'assetsid': id.get('id'), "assetgroupL": assetgroupL, "userinfL": userinfL, "scriptL": scriptL,
                   "hosttypeL": hosttypeL})

@login_required
def asset_group_edit(request):
    id = request.GET
    print(id.get('id'))
    infos = models.assetgroup.objects.filter(id=id.get('id')).values().first()
    print(val_to(infos))
    return render(request, 'asset-group/asset-group-edit.html', {'assetgroupid': id.get('id')})

@login_required
def scripts_group_edit(request):
    id = request.GET
    print(id.get('id'))
    infos = models.ScriptsGroup.objects.filter(id=id.get('id')).values().first()
    print(val_to(infos))
    return render(request, 'scripts/scripts-group-edit.html', {'scriptsgroupid': id.get('id')})

@login_required
def edit_init_base_env(request):
    id = request.GET
    print(id.get('id'))
    # infos=models.initenv.objects.filter(id=id.get('id')).values().first()
    # print(val_to(infos))
    return render(request, 'initenv/start-init-base-env.html', {'initid': id.get('id'), "webssh": websshinfo, })

@login_required
def assets_show(request):
    return render(request, 'assets/asset-show.html')

@login_required
def assets(request):
    return render(request, 'assets/assets.html')

@login_required
def init_base_env(request):
    return render(request, 'initenv/init-base-env.html')


@login_required
def init_system_kickstart(request):
    return render(request, 'initsystem/init-base-system-kickstarts.html')


@login_required
def edit_system_kickstart(request):
    kickstart=request.GET.get("kickstart")
    return render(request, 'initsystem/edit-init-system-kickstarts.html',{"kickstart":kickstart})


@login_required
def add_system_kickstart(request):
    return render(request, 'initsystem/add-init-system-kickstarts.html')



@login_required
def init_system_snippets(request):
    return render(request, 'initsystem/init-base-system-snippets.html')


@login_required
def edit_system_snippets(request):
    snippets=request.GET.get("snippets")
    return render(request, 'initsystem/edit-init-system-snippets.html',{"snippets":snippets})


@login_required
def add_system_snippets(request):
    return render(request, 'initsystem/add-init-system-snippets.html')


@login_required
def init_system_system(request):
    return render(request, 'initsystem/init-base-system-system.html')


@login_required
def edit_system_system(request):
    system=request.GET.get("system")
    cobbler=CobblerApi.init_system_api.run()
    kickstart = cobbler.get_kickstart_templates()
    profile = cobbler.find_profiles()
    return render(request, 'initsystem/edit-init-system-system.html',{"system":system,"kickstart":kickstart,"profile":profile})


@login_required
def add_system_system(request):
    cobbler=CobblerApi.init_system_api.run()

    kickstart = cobbler.get_kickstart_templates()
    profile = cobbler.find_profiles()
    return render(request, 'initsystem/add-init-system-system.html',{"kickstart":kickstart,"profile":profile})



@login_required
def init_system_task(request):
    return render(request, 'initsystem/init-base-system-task.html')


@login_required
def edit_system_task(request):
    task=request.GET.get("task")
    cobbler=CobblerApi.init_system_api.run()
    kickstart = cobbler.get_kickstart_templates()
    profile = cobbler.find_profiles()
    return render(request, 'initsystem/edit-init-system-task.html',{"task":task,"kickstart":kickstart,"profile":profile})


@login_required
def add_system_task(request):
    cobbler=CobblerApi.init_system_api.run()

    kickstart = cobbler.get_kickstart_templates()
    profile = cobbler.find_profiles()
    return render(request, 'initsystem/add-init-system-task.html',{"kickstart":kickstart,"profile":profile})

@login_required
def info_system_task(request):
    task=request.GET.get("task")
    return render(request,'initsystem/info-init-system-task.html',{"task":task})


@login_required
def operations(request):
    import os,uuid
    scrobj = models.Scripts.objects.filter(id=8).first()
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    shellname = os.path.join(BASE_DIR, 'scripts', str(uuid.uuid1()))
    print(scrobj.context)
    # context = scrobj.context.encode(encoding="utf-8")
    # with open(shellname, 'wb') as f:
    #     f.write(context)
    return render(request, 'operations/operations.html')

@login_required
def assets_add(request):
    assetgrouplists = models.assetgroup.objects.filter(status=0).values('id', 'groupname')
    loginusers = models.AssetLoginUser.objects.filter(status=0).all().values('id', 'username', 'status')
    scriptlists = models.Scripts.objects.all().values('id', 'zwname', 'qpname')
    hostypelists = models.HostType.objects.all().values('id', 'name', 'type')

    assetgroupL = []
    userinfL = []
    scriptL = []
    hosttypeL = []
    for chobj in assetgrouplists:
        assetgroupL.append(val_to(chobj))

    for usrobj in loginusers:
        userinfL.append(val_to(usrobj))

    for scrobj in scriptlists:
        scriptL.append(val_to(scrobj))

    for hosttypeobj in hostypelists:
        hosttypeL.append(val_to(hosttypeobj))

    print(assetgroupL)
    print(userinfL)

    return render(request, 'assets/add-assets.html',
                  {"assetgroupL": assetgroupL, "userinfL": userinfL, "scriptL": scriptL, "hosttypeL": hosttypeL})

@login_required
def add_init_base_env(request):
    # assetgrouplists = models.assetgroup.objects.all().values('id', 'assetinfo__hostname')
    # loginusers = models.AssetLoginUser.objects.filter(status=0).all().values('id', 'username', 'status')
    scriptlists = models.Scripts.objects.all().values('id', 'zwname', 'qpname')
    # hostypelists = models.HostType.objects.all().values('id', 'name', 'type')

    assetlists = models.AssetInfo.objects.values()

    # assetgroupL = []
    # userinfL = []
    scriptL = []
    # hosttypeL = []
    assetlistsL=[]
    # for chobj in assetgrouplists:
    #     assetgroupL.append(val_to(chobj))

    # for usrobj in loginusers:
    #     userinfL.append(val_to(usrobj))

    for scrobj in scriptlists:
        scriptL.append(val_to(scrobj))

    for assetobj in assetlists:
        assetlistsL.append(val_to(assetobj))

    # print(assetgroupL)
    # print(userinfL)
    # print(scriptL)

    return render(request, 'initenv/add-init-base-env.html',
                  {"scriptL": scriptL, "assetlistsL": assetlistsL})

@login_required
def add_remote_init_base_env(request):
    # assetgrouplists = models.assetgroup.objects.all().values('id', 'assetinfo__hostname')
    loginusers = models.AssetLoginUser.objects.filter(status=0).all().values('id', 'username', 'status')
    scriptlists = models.Scripts.objects.all().values('id', 'zwname', 'qpname')
    hostypelists = models.HostType.objects.all().values('id', 'name', 'type')

    assetgroupL = []
    userinfL = []
    scriptL = []
    hosttypeL = []
    # for chobj in assetgrouplists:
    #     assetgroupL.append(val_to(chobj))

    for usrobj in loginusers:
        userinfL.append(val_to(usrobj))

    for scrobj in scriptlists:
        scriptL.append(val_to(scrobj))

    for hosttypeobj in hostypelists:
        hosttypeL.append(val_to(hosttypeobj))

    # print(assetgroupL)
    print(userinfL)
    print(scriptL)

    return render(request, 'initenv/add-remote-init-base-env.html',{"scriptL": scriptL})



@login_required
def userinfos(request):
    return render(request, 'users/userinfos.html')

@login_required
def scripts(request):
    return render(request, 'scripts/scripts.html')

@login_required
def api_asset_group_get(request):
    data = request.POST.get('data')
    if data:
        postdata = json.loads(data)
        print(postdata)
        id = postdata.get('id')
        print(id)
        assetgrouplists = models.assetgroup.objects.filter(id=id).values('id', 'groupname', 'status', 'uptime',
                                                       'addtime', 'remarks').first()
        return JsonResponse(val_to(assetgrouplists))

    assetgrouplists = models.assetgroup.objects.all().values('id', 'groupname', 'status', 'uptime',
                                                       'addtime', 'remarks')
    datainfo = []
    for assetgroupinfo in assetgrouplists:
        datainfo.append(val_to(assetgroupinfo))
    userinfo = {
        "code": 0,
        "msg": "",
        "count": assetgrouplists.count(),
        "data": datainfo
    }
    return JsonResponse(userinfo)

@login_required
def api_scripts_group_get(request):
    data = request.POST.get('data')
    if data:
        postdata = json.loads(data)
        print(postdata)
        id = postdata.get('id')
        print(id)
        assetgrouplists = models.ScriptsGroup.objects.filter(id=id).values('id', 'groupname', 'status', 'uptime',
                                                       'addtime', 'remarks','path').first()
        return JsonResponse(val_to(assetgrouplists))

    Scriptsgrouplists = models.ScriptsGroup.objects.all().values('id', 'groupname', 'status', 'uptime',
                                                       'addtime', 'remarks','path')
    datainfo = []

    for Scriptsgroupinfo in Scriptsgrouplists:
        scount=models.Scripts.objects.filter(scriptsgroup_id=Scriptsgroupinfo.get("id")).count()
        sinfos=val_to(Scriptsgroupinfo)
        sinfos["scount"]=scount
        datainfo.append(sinfos)
    userinfo = {
        "code": 0,
        "msg": "",
        "count": Scriptsgrouplists.count(),
        "data": datainfo
    }
    return JsonResponse(userinfo)


@login_required
def api_asset_group_search(request):
    postdata = request.POST
    data = postdata.get("data")
    limit = postdata.get("limit")
    page = postdata.get("page")

    if data:
        postdata = json.loads(data)
        print(postdata)
        keywords = postdata.get('keywords')
        if keywords == "":
            assetgrouplists = models.assetgroup.objects.all().values('id', 'city_id', 'city_qp', 'city_zw', 'status',
                                                               'client', 'addtime', 'remarks')
            datainfo = []
            for assetgroupinfo in assetgrouplists:
                datainfo.append(val_to(assetgroupinfo))
            userinfo = {
                "code": 0,
                "msg": "",
                "count": assetgrouplists.count(),
                "data": datainfo
            }
            return JsonResponse(userinfo)
        alllists = []

        if keywords.isdigit():
            assetgrouplists_id = models.assetgroup.objects.filter(city_id=keywords).values('id', 'city_id', 'city_qp',
                                                                                     'city_zw', 'status', 'client',
                                                                                     'addtime', 'remarks')
            for id_obj in assetgrouplists_id:
                alllists.append(json.dumps(val_to(id_obj)))
        assetgrouplists_city_zw = models.assetgroup.objects.filter(city_zw=keywords).values('id', 'city_id', 'city_qp',
                                                                                      'city_zw', 'status', 'client',
                                                                                      'addtime', 'remarks')
        assetgrouplists_city_qp = models.assetgroup.objects.filter(city_qp=keywords).values('id', 'city_id', 'city_qp',
                                                                                      'city_zw', 'status', 'client',
                                                                                      'addtime', 'remarks')

        for id_obj in assetgrouplists_city_zw:
            alllists.append(json.dumps(val_to(id_obj)))

        for id_obj in assetgrouplists_city_qp:
            alllists.append(json.dumps(val_to(id_obj)))

        print(alllists)
        infoslists = list(set(alllists))
        print(infoslists)
        # return JsonResponse(infoslists)
        newinfos = []
        for ina in infoslists:
            newinfos.append(json.loads(ina))

        userinfo = {
            "code": 0,
            "msg": "",
            "count": len(newinfos),
            "data": newinfos
        }
        return JsonResponse(userinfo)

@login_required
def api_asset_group_add(request):
    data = request.POST.get('data')
    channposts = json.loads(data)
    print(channposts)
    models.assetgroup.objects.create(**channposts)
    return JsonResponse({"status": 0})


@login_required
def api_init_system_kickstart_add(request):
    data = json.loads(request.POST.get('data'))
    kickstart = data.get("kickstart")
    context = data.get("context")
    print(data)
    cobbler=CobblerApi.init_system_api.run()
    kickstartlist=cobbler.get_kickstart_templates()
    if len(kickstartlist)==0:
        kspath="/var/lib/cobbler/kickstarts/"
    else:
        kspath=os.path.dirname(kickstartlist[0]["kickstart"])

    kickstart=Path(os.path.join(kspath,kickstart)).as_posix()
    try:
        infos=cobbler.read_or_write_kickstart_template(kickstart,context)
        print(infos)
        return JsonResponse({"status": 0,"message":"操作成功"})
    except Exception as e:
        return JsonResponse({"status": 1,"message":str(e)})


@login_required
def api_init_system_snippets_add(request):
    data = json.loads(request.POST.get('data'))
    snippets = data.get("snippets")
    context = data.get("context")
    print(data)
    cobbler=CobblerApi.init_system_api.run()
    snippetslist=cobbler.get_snippets()
    if len(snippetslist)==0:
        kspath="/var/lib/cobbler/snippets/"
    else:
        kspath=os.path.dirname(snippetslist[0]["snippets"])

    snippets=Path(os.path.join(kspath,snippets)).as_posix()
    try:
        infos=cobbler.read_or_write_snippet(snippets,context)
        print(infos)
        return JsonResponse({"status": 0,"message":"操作成功"})
    except Exception as e:
        return JsonResponse({"status": 1,"message":str(e)})



@login_required
def api_init_system_system_add(request):
    data = json.loads(request.POST.get('data'))
    # print(data)
    post_name = data.get("name")
    cobbler=CobblerApi.init_system_api.run()
    systemlist=cobbler.find_system()
    for system_name in systemlist:
        if post_name == system_name:
            return JsonResponse({"status": 2, "message": "系统名称已经存在，无法添加"})

    try:
        # infos=cobbler.read_or_write_snippet(system,context)
        # print(infos)
        if data.get("netboot_enabled") == "0":
            netboot_enabled=True
        else:
            netboot_enabled=False

        cobbler.create_or_update_system(post_name, data.get("mac_address"), data.get("ip_address"),data.get("profile"),
                                        data.get("netmask"), data.get("gateway"), data.get("interface"),
                                        data.get("hostname"),data.get("name_servers"),netboot_enabled)
        return JsonResponse({"status": 0,"message":"操作成功"})
    except Exception as e:
        return JsonResponse({"status": 1,"message":str(e)})



@login_required
def api_init_system_task_add(request):
    data = json.loads(request.POST.get('data'))
    try:
        # if data.get("netboot_enabled") == "0":
        #     netboot_enabled=True
        # else:
        #     netboot_enabled=False
        netboot_enabled = True
        models.CobblerSystemInit.objects.create(mac_address=data.get("mac_address"), ip_address=data.get("ip_address"),
                                                profile=data.get("profile"),netmask=data.get("netmask"),
                                                gateway=data.get("gateway"), interface=data.get("interface"),
                                        hostname=data.get("hostname"),name_servers=data.get("name_servers"),
                                                netboot_enabled=netboot_enabled,kickstart=data.get("kickstart"))
        return JsonResponse({"status": 0,"message":"操作成功"})
    except Exception as e:
        return JsonResponse({"status": 1,"message":str(e)})


@login_required
def api_init_system_task_run(request):
    message = "任务添加成功"
    postdata = json.loads(request.POST.get('data'))
    task = postdata.get("id")
    task_info_obj = models.CobblerSystemInit.objects.filter(id=task).values().first()
    post_name = "{}-{}".format(task_info_obj.get("hostname"),task_info_obj.get("ip_address"))

    cobbler=CobblerApi.init_system_api.run()
    systemlist=cobbler.find_system()
    for system_name in systemlist:
        if post_name == system_name:
            # return JsonResponse({"status": 2, "message": "系统名称已经存在，无法添加"})
            message="任务更新成功"

    try:

        data = task_info_obj
        cobbler.create_or_update_system(post_name, data.get("mac_address"), data.get("ip_address"),data.get("profile"),
                                        data.get("netmask"), data.get("gateway"), data.get("interface"),
                                        data.get("hostname"),data.get("name_servers"),True)

        return JsonResponse({"status": 0,"message":message})
    except Exception as e:
        return JsonResponse({"status": 1,"message":str(e)})


@login_required
def api_scripts_group_add(request):
    data = request.POST.get('data')
    channposts = json.loads(data)
    print(channposts)
    models.ScriptsGroup.objects.create(**channposts)
    return JsonResponse({"status": 0})

@login_required
def api_assets_add(request):
    data = request.POST.get('data')
    channposts = json.loads(data)
    print(channposts)
    ipv4=str(channposts.get('network_ip'))

    result = re.findall(
        r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b", ipv4)

    if result:
        print(result)
    else:
        return JsonResponse({"status": 1, "message": "ip地址校验失败"})
    try:
        models.AssetInfo.objects.create(assetgroup_id=channposts.get("groupname"), user_id=channposts.get("user"),
                                        network_ip=channposts.get('network_ip'), hostname=channposts.get('hostname'),
                                        bandwidth=int(channposts.get('bandwidth')), port=int(channposts.get('port')),
                                        remarks=channposts.get('remarks'))
        return JsonResponse({"status": 0})
    except Exception as e:
        print(e)
        return JsonResponse({"status": 1,"message":str(e)})

@login_required
def api_users_add(request):
    data = request.POST.get('data')
    channposts = json.loads(data)
    print(channposts)
    models.AssetLoginUser.objects.create(**channposts)
    return JsonResponse({"status": 0})

@login_required
def api_scripts_add(request):
    data = request.POST.get('data')
    channposts = json.loads(data)
    scriptgroupid=channposts.get("groupname")
    print(channposts)
    print(scriptgroupid)
    models.Scripts.objects.create(zwname=channposts.get("zwname"),qpname=channposts.get("qpname"),scriptsgroup_id=scriptgroupid,
                                  context=channposts.get("context"),
                                  options=channposts.get("options"),remarks=channposts.get("remarks"))
    return JsonResponse({"status": 0})

@login_required
def api_asset_group_edit(request):
    data = request.POST.get('data')
    assetgroupid = request.POST.get('assetgroupid')
    print("assetgroupid", assetgroupid)
    channposts = json.loads(data)
    channposts["uptime"]=timezone.now()

    print(channposts)
    try:
        models.assetgroup.objects.filter(id=assetgroupid).update(**channposts)
        return JsonResponse({"status": 0})
    except Exception as e:
        return JsonResponse({"status": 1})

@login_required
def api_init_system_kickstart_edit(request):
    data = json.loads(request.POST.get('data'))
    kickstart = data.get("kickstart")
    context = data.get("context")
    cobbler=CobblerApi.init_system_api.run()

    try:
        cobbler.read_or_write_kickstart_template(kickstart,context)
        return JsonResponse({"status": 0,"message":"操作成功"})
    except Exception as e:
        return JsonResponse({"status": 1,"message":str(e)})


@login_required
def api_init_system_snippets_edit(request):
    data = json.loads(request.POST.get('data'))
    snippets = data.get("snippets")
    context = data.get("context")
    cobbler=CobblerApi.init_system_api.run()
    try:
        cobbler.read_or_write_snippet(snippets,context)
        return JsonResponse({"status": 0,"message":"操作成功"})
    except Exception as e:
        return JsonResponse({"status": 1,"message":str(e)})


@login_required
def api_init_system_system_edit(request):
    data = json.loads(request.POST.get('data'))
    print(data)
    cobbler=CobblerApi.init_system_api.run()

    try:
        # infos=cobbler.read_or_write_snippet(system,context)
        # print(infos)
        if data.get("netboot_enabled") == "0":
            netboot_enabled=True
        else:
            netboot_enabled=False
        cobbler.create_or_update_system(data.get("name"), data.get("mac_address"), data.get("ip_address"),data.get("profile"),
                                        data.get("netmask"), data.get("gateway"), data.get("interface"),
                                        data.get("hostname"),data.get("name_servers"),netboot_enabled)
        return JsonResponse({"status": 0,"message":"操作成功"})
    except Exception as e:
        return JsonResponse({"status": 1,"message":str(e)})



@login_required
def api_init_system_task_edit(request):
    data = json.loads(request.POST.get('data'))
    # print(data)
    # cobbler=CobblerApi.init_system_api.run()

    try:
        # infos=cobbler.read_or_write_snippet(system,context)
        # print(infos)
        netboot_enabled = True
        models.CobblerSystemInit.objects.filter(id=data.get("id")).update(mac_address=data.get("mac_address"), ip_address=data.get("ip_address"),
                                                profile=data.get("profile"),netmask=data.get("netmask"),
                                                gateway=data.get("gateway"), interface=data.get("interface"),
                                        hostname=data.get("hostname"),name_servers=data.get("name_servers"),
                                                netboot_enabled=netboot_enabled,kickstart=data.get("kickstart"))
        return JsonResponse({"status": 0,"message":"操作成功"})
    except Exception as e:
        return JsonResponse({"status": 1,"message":str(e)})


@login_required
def api_scripts_group_edit(request):
    data = request.POST.get('data')
    assetgroupid = request.POST.get('assetgroupid')
    print("assetgroupid", assetgroupid)
    channposts = json.loads(data)
    channposts["uptime"]=timezone.now()

    print(channposts)
    try:
        models.ScriptsGroup.objects.filter(id=assetgroupid).update(**channposts)
        return JsonResponse({"status": 0})
    except Exception as e:
        return JsonResponse({"status": 1})


@login_required
def api_assets_edit(request):
    data = request.POST.get('data')
    assetsid = request.POST.get('assetsid')
    print("assetsid", assetsid)
    channposts = json.loads(data)
    channposts["uptime"]=timezone.now()
    print(channposts)
    result = re.findall(
        r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b", channposts["network_ip"])

    if result:
        print(result)
    else:
        return JsonResponse({"status": 1, "message": "ip地址校验失败"})
    try:
        models.AssetInfo.objects.filter(id=assetsid).update(**channposts)
        return JsonResponse({"status": 0})
    except Exception as e:
        return JsonResponse({"status": 1})

@login_required
def api_asset_group_del(request):
    data = request.POST.get('data')
    channposts = json.loads(data)
    print(channposts)
    try:
        models.assetgroup.objects.filter(groupname=channposts.get('groupname'), id=channposts.get('id')).delete()
        return JsonResponse({"status": 0})
    except Exception as e:
        print(e)
        return JsonResponse({"status": 1})

@login_required
def api_init_system_kickstart_del(request):
    data = request.POST.get('data')
    channposts = json.loads(data)
    kickstart=channposts.get("kickstart")
    cobbler=CobblerApi.init_system_api.run()
    if cobbler.is_kickstart_in_use(kickstart):
        return JsonResponse({"status": 1,"message":"该文件被使用中，无法删除"})
    else:
        cobbler.read_or_write_kickstart_template(kickstart,-1)
        return JsonResponse({"status": 0,"message":"删除成功"})



@login_required
def api_init_system_snippets_del(request):
    data = request.POST.get('data')
    channposts = json.loads(data)
    snippets=channposts.get("snippets")
    cobbler=CobblerApi.init_system_api.run()
    status,tep=cobbler.is_snippets_in_use(snippets,cobbler.get_kickstart_templates())
    if status:
        return JsonResponse({"status": 1,"message":"该文件被使用中，无法删除"})
    else:
        cobbler.read_or_write_snippet(snippets,-1)
        return JsonResponse({"status": 0,"message":"删除成功"})


@login_required
def api_init_system_system_del(request):
    data = request.POST.get('data')
    channposts = json.loads(data)
    system=channposts.get("name")
    cobbler=CobblerApi.init_system_api.run()
    try:
        cobbler.remove_system(system)
        return JsonResponse({"status": 0,"message":"删除成功"})
    except Exception as e:
        return JsonResponse({"status": 1,"message":str(e)})


@login_required
def api_init_system_task_del(request):
    data = request.POST.get('data')
    channposts = json.loads(data)
    hostname=channposts.get("hostname")
    id = channposts.get("id")
    ip = channposts.get("ip_address")
    cobbler=CobblerApi.init_system_api.run()
    try:
        system = "{}-{}".format(hostname,ip)
        info = cobbler.get_system(system)
        if info != "~":
            cobbler.remove_system(system)
        models.CobblerSystemInit.objects.filter(id=id).delete()
        return JsonResponse({"status": 0,"message":"删除成功"})
    except Exception as e:
        return JsonResponse({"status": 1,"message":str(e)})


@login_required
def api_scripts_group_del(request):
    data = request.POST.get('data')
    channposts = json.loads(data)
    print(channposts)
    if models.Scripts.objects.filter(scriptsgroup_id=channposts.get("id")).count() !=0:
        return JsonResponse({"status": 1,"message":"脚本数量不为0"})

    try:
        models.ScriptsGroup.objects.filter(id=channposts.get('id'), groupname=channposts.get('groupname')).delete()
        return JsonResponse({"status": 0})
    except Exception as e:
        print(e)
        return JsonResponse({"status": 1,"message":str(e)})


@login_required
def api_assets_del(request):
    data = request.POST.get('data')
    channposts = json.loads(data)
    print(channposts)
    try:
        models.AssetInfo.objects.filter(hostname=channposts.get('hostname'),
                                        network_ip=channposts.get('network_ip')).delete()
        return JsonResponse({"status": 0})
    except Exception as e:
        print(e)
        return JsonResponse({"status": 1})

@login_required
def api_city_get(request):


    citylistsinfos=[]
    for assetgroupobj in models.assetgroup.objects.all():
        hostobjlists = models.AssetInfo.objects.filter(assetgroup=assetgroupobj).all()
        cityinfo=models.CityInfos.objects.filter(assetgroupid=assetgroupobj).first()
        if cityinfo:
            menuUrl="服务端SVN：{}  客户端SVN：{}  客户端版本：{}".format(cityinfo.serversvnversion,cityinfo.clientvnversion,0)
        else:
            menuUrl="暂无记录"
        citylistsinfos.append({
            "authorityId": assetgroupobj.id,
            "authorityName": assetgroupobj.groupname,
            "orderNumber":  assetgroupobj.id,
            "menuUrl": menuUrl,
            "menuIcon": "",
            "createTime": "2018/06/29 11:05:41",
            "authority": "资产组",
            "checked": 0,
            "updateTime": "2018/07/13 09:13:42",
            "isMenu": 0,
            "parentId": -1,
            "hostid": assetgroupobj.id,
        })
        for hostobj in hostobjlists:
            citylistsinfos.append({
                "authorityId": assetgroupobj.id*99999+hostobj.id,
                "authorityName": hostobj.hostname,
                "orderNumber": assetgroupobj.id*99999+hostobj.id,
                "menuUrl": "",
                "menuIcon": "",
                "createTime": hostobj.addtime,
                "authority": hostobj.network_ip,
                "checked": 0,
                "updateTime": "2018/07/13 09:13:42",
                "isMenu": 1,
                "parentId":  assetgroupobj.id,
                "hostid":hostobj.id,
            })


    infos = {
        "code": 0,
        "msg": "",
        "count": len(citylistsinfos),
        "data": citylistsinfos
    }
    print(infos)
    return JsonResponse(infos)

@login_required
def api_assets_get(request):
    data = request.POST.get('data')
    if data:
        postdata = json.loads(data)
        print(postdata)
        id = postdata.get('id')
        print(id)
        loginusers = models.AssetInfo.objects.filter(id=id).values('id', 'hostname', 'assetgroup',
                                                                   'network_ip', 'cpu', 'memory', 'disk',
                                                                   'port', 'bandwidth', 'addtime','uptime',
                                                                   'user').first()
        return JsonResponse(val_to(loginusers))

    loginusers = models.AssetInfo.objects.all().values('id', 'hostname', 'assetgroup__groupname', 'network_ip', 'cpu',
                                                       'memory', 'disk', 'uptime','addtime')
    datainfo = []
    for user in loginusers:
        datainfo.append(val_to(user))
    userinfo = {
        "code": 0,
        "msg": "",
        "count": len(datainfo),
        "data": datainfo
    }
    return JsonResponse(userinfo)

@login_required
def api_init_system_kickstart_get(request):
    data = request.POST.get('data')
    cobbler=CobblerApi.init_system_api.run()
    if data:
        postdata = json.loads(data)
        kickstart = postdata.get("kickstart")
        context=cobbler.read_or_write_kickstart_template(kickstart,'',True)
        return JsonResponse({"kickstart":kickstart,"context":context})

    kickstartlist=cobbler.get_kickstart_templates()
    print(kickstartlist)

    kickstartinfo = {
        "code": 0,
        "msg": "",
        "count": len(kickstartlist),
        "data": kickstartlist
    }
    return JsonResponse(kickstartinfo)



@login_required
def api_init_system_snippets_get(request):
    data = request.POST.get('data')
    cobbler=CobblerApi.init_system_api.run()
    if data:
        postdata = json.loads(data)
        snippets = postdata.get("snippets")
        context=cobbler.read_or_write_snippet(snippets,'',True)
        return JsonResponse({"snippets":snippets,"context":context})

    snippetslist=cobbler.get_snippets()
    # print(snippetslist)

    snippetsinfo = {
        "code": 0,
        "msg": "",
        "count": len(snippetslist),
        "data": snippetslist
    }
    return JsonResponse(snippetsinfo)


@login_required
def api_init_system_system_get(request):
    data = request.POST.get('data')
    cobbler=CobblerApi.init_system_api.run()
    system_info_list=[]
    systemlist=cobbler.find_system()
    if data:
        postdata = json.loads(data)
        print(postdata)
        systemlist=[postdata.get("system")]
        # system = postdata.get("system")
        # context=cobbler.read_or_write_snippet(system,'',True)
        # return JsonResponse({"message":postdata})


    for system_name in systemlist:
        system_info = cobbler.get_system(system_name)
        print(system_info)
        hostname =system_info.get("hostname")
        for k, v in system_info.get("interfaces").items():
            interface = k
            mac_address=v.get("mac_address")
            netmask=v.get("netmask")
            ip_address=v.get("ip_address")

        system_info_list.append({"name":system_info.get("name"),"interface":interface,
                                 "gateway":system_info.get("gateway"),"hostname":hostname,"mac_address":mac_address,
                                 "netmask":netmask,"ip_address":ip_address,
                                 "kernel_options":json.dumps(system_info.get("kernel_options")),
                                 "name_servers":system_info.get("name_servers"),
                                 "netboot_enabled":system_info.get("netboot_enabled"),
                                 "kickstart":system_info.get("kickstart"),"profile":system_info.get("profile")
                                 })
    systeminfo = {
        "code": 0,
        "msg": "",
        "count": len(system_info_list),
        "data": system_info_list
    }
    return JsonResponse(systeminfo)




@login_required
def api_init_system_task_get(request):
    data = request.POST.get('data')
    flag = False
    if data:
        task = json.loads(data).get("task")
        taskobjlist = models.CobblerSystemInit.objects.filter(id=task).values("id", "hostname", "interface", "gateway",
                                                                    "mac_address",
                                                                    "netmask", "netboot_enabled", "kickstart",
                                                                    "profile",
                                                                    "kernel_options", "ip_address", "name_servers",
                                                                    "starttime", "endtime", "successcount",
                                                                    "installcount",
                                                                    "addtime", "uptime", "remarks", "status")
    else:
        flag=True

        '''
        获取cobbler system 安装状态
        
        '''
        try:
            cobbler = CobblerApi.init_system_api.run()
            # task_m=models.CobblerSystemInit.objects.exclude(status="finished")
            task_m=models.CobblerSystemInit.objects.all()
            for task_obj in task_m:
                system_name = "{}-{}".format(task_obj.hostname,task_obj.ip_address)
                system_status = cobbler.get_system_status(system_name)
                if system_status:
                    models.CobblerSystemInit.objects.filter(id=task_obj.id).update(installcount=system_status.get("initcount"),
                                                                                      successcount=system_status.get("successcount"),
                                                                                   status=system_status.get("status"),
                                                                                   endtime=system_status.get("endtime"),
                                                                                   starttime=system_status.get("starttime"),
                                                                                   )
        except Exception as e:
            print(e)
        taskobjlist = models.CobblerSystemInit.objects.all().values()

    task_info_list = []
    for task in taskobjlist:
        tasks = val_to(task)
        if flag:
            tasks["kickstart"]=os.path.basename(tasks["kickstart"])
        try:
            tasks["spendtime"]=spendtime(tasks["starttime"],tasks["endtime"])
        except :
            tasks["spendtime"]=""
        task_info_list.append(tasks)
    systeminfo = {
        "code": 0,
        "msg": "",
        "count": len(task_info_list),
        "data": task_info_list
    }
    print(systeminfo)
    return JsonResponse(systeminfo)



@login_required
def api_initbase_get(request):
    getdata = request.GET
    initid = getdata.get("initid")
    if initid:
        loginusers = models.initenv.objects.filter(id=initid).values('id', 'network_ip', 'username',
                                                                     'addtime',
                                                                      'status','remarks', 'scripts__zwname')
    else:

        loginusers = models.initenv.objects.all().values('id', 'network_ip', 'username',  'addtime',
                                                          'remarks','status', 'scripts__zwname')
    datainfo = []
    for user in loginusers:
        datainfo.append(val_to(user))
    userinfo = {
        "code": 0,
        "msg": "",
        "count": len(datainfo),
        "data": datainfo
    }
    print(userinfo)

    return JsonResponse(userinfo)

@login_required
def api_webshell_get(request):
    getdata = request.GET
    assetsid = getdata.get("assetsid")
    print(getdata)
    if assetsid:
        loginusers = models.AssetInfo.objects.filter(id=assetsid).values('id', 'network_ip',
                                                                         'remarks','hostname', 'assetgroup__groupname','addtime','uptime')
    else:
        loginusers=[]
    datainfo = []
    for user in loginusers:
        datainfo.append(val_to(user))
    userinfo = {
        "code": 0,
        "msg": "",
        "count": len(datainfo),
        "data": datainfo
    }
    print(userinfo)

    return JsonResponse(userinfo)

@login_required
def api_initbase_add(request):
    data = request.POST.get('data')
    channposts = json.loads(data)
    print(channposts)

    models.initenv.objects.create(
                                  scripts_id=channposts.get("scripts"),
                                  network_ip=channposts.get('network_ip'), username=channposts.get('username').strip(" "),
                                  password=channposts.get('password').strip(" ").strip(" "), port=int(channposts.get('port').strip(" ")),
                                  remarks=channposts.get('remarks'))

    if channposts.get("syncstatus") and channposts.get("syncstatus") == "0":
        models.AssetInfo.objects.create(citys_id=channposts.get("citys"), user_id=channposts.get("user"),
                                        type_id=channposts.get("hostypeid"),
                                        network_ip=channposts.get('network_ip'), hostname=channposts.get('hostname'),
                                        bandwidth=int(channposts.get('bandwidth')), port=int(channposts.get('port')),
                                        remarks=channposts.get('remarks'))

    # models.initenv.objects.create(**channposts)
    return JsonResponse({"status": 0})


@login_required
def api_remote_initbase_add(request):
    data = request.POST.get('data')
    try:
        channposts = json.loads(data)
        print(channposts)
        flag = channposts.get("flag")
        if flag== "0":
            # 资产添加
            assetobj = models.AssetInfo.objects.filter(id=channposts.get("asset-id")).get()
            userobj = assetobj.user
            models.initenv.objects.create(scripts_id=channposts.get("scripts"),
                                          network_ip=assetobj.network_ip, username=userobj.username,
                                          password=userobj.password, port=int(assetobj.port),
                                          remarks=channposts.get('remarks'),flag=0)
        elif flag == "1":
            # 远端添加
            models.initenv.objects.create(
                                          scripts_id=channposts.get("scripts"),
                                          network_ip=channposts.get('network_ip'), username=channposts.get('username').strip(" "),
                                          password=channposts.get('password').strip(" ").strip(" "), port=int(channposts.get('port').strip(" ")),
                                          remarks=channposts.get('remarks'),flag=1)

            # if channposts.get("syncstatus") and channposts.get("syncstatus") == "0":
            #     models.AssetInfo.objects.create(citys_id=channposts.get("citys"), user_id=channposts.get("user"),
            #                                     type_id=channposts.get("hostypeid"),
            #                                     network_ip=channposts.get('network_ip'), hostname=channposts.get('hostname'),
            #                                     bandwidth=int(channposts.get('bandwidth')), port=int(channposts.get('port')),
            #                                     remarks=channposts.get('remarks'))

        # models.initenv.objects.create(**channposts)
        else:
            return JsonResponse({"status": 2, "message": "flag verify failed"})
        return JsonResponse({"status": 0})
    except Exception as e:
        print(e)
        return JsonResponse({"status": 1,"message":str(e)})

@login_required
def api_users_get(request):
    data = request.POST.get('data')
    if data:
        postdata = json.loads(data)
        print(postdata)
        id = postdata.get('id')
        print(id)
        loginusers = models.AssetLoginUser.objects.filter(id=id).values('id', 'username', 'status', 'addtime',
                                                                        'remarks','uptime').first()
        return JsonResponse(val_to(loginusers))

    loginusers = models.AssetLoginUser.objects.all().values('id', 'username', 'status', 'addtime', 'remarks','uptime')
    datainfo = []
    for user in loginusers:
        datainfo.append(val_to(user))
    userinfo = {
        "code": 0,
        "msg": "",
        "count": len(datainfo),
        "data": datainfo
    }
    return JsonResponse(userinfo)

@login_required
def api_scripts_get(request):
    data = request.POST.get('data')
    if data:
        postdata = json.loads(data)
        print(postdata)
        id = postdata.get('id')
        print(id)
        loginusers = models.Scripts.objects.filter(id=id).values('id', 'zwname', 'qpname', 'scriptsgroup', 'context',
                                                                 'addtime', 'remarks', 'options').first()
        return JsonResponse(val_to(loginusers))

    loginusers = models.Scripts.objects.all().values('id', 'zwname', 'qpname', 'scriptsgroup__path', 'addtime', 'remarks',
                                                     'options')
    datainfo = []
    for user in loginusers:
        datainfo.append(val_to(user))
    userinfo = {
        "code": 0,
        "msg": "",
        "count": len(datainfo),
        "data": datainfo
    }
    return JsonResponse(userinfo)

@login_required
def api_users_edit(request):
    data = request.POST.get('data')
    userid = request.POST.get('userid')
    print("userid", userid)
    channposts = json.loads(data)
    print(channposts)
    try:
        if channposts.get("password") == "":
            channposts.pop("password")
        models.AssetLoginUser.objects.filter(id=userid).update(**channposts)
        return JsonResponse({"status": 0})

    except Exception as e:
        print(e)
        return JsonResponse({"status": 1})

@login_required
def api_scripts_edit(request):
    data = request.POST.get('data')
    scriptsid = request.POST.get('scriptsid')
    print("scriptsid", scriptsid)
    channposts = json.loads(data)
    print(channposts)
    try:
        models.Scripts.objects.filter(id=scriptsid).update(**channposts)
        return JsonResponse({"status": 0})
    except Exception as e:
        print(e)
        return JsonResponse({"status": 1})

@login_required
def api_users_del(request):
    data = request.POST.get('data')
    postdata = json.loads(data)
    print(postdata)
    models.AssetLoginUser.objects.filter(username=postdata.get('username'), status=postdata.get('status')).delete()
    return JsonResponse({"status": 0})

@login_required
def api_scripts_del(request):
    data = request.POST.get('data')
    postdata = json.loads(data)
    print(postdata)
    models.Scripts.objects.filter(qpname=postdata.get('qpname'), id=postdata.get('id')).delete()
    return JsonResponse({"status": 0})

@login_required
def api_initbase_del(request):
    data = request.POST.get('data')
    postdata = json.loads(data)
    print(postdata)
    models.initenv.objects.filter(network_ip=postdata.get('network_ip'), id=postdata.get('id')).delete()
    return JsonResponse({"status": 0})


@csrf_exempt
def api_hosts_get(request):
    remoteaddr = request.get_host()
    if remoteaddr.split(":")[0] in "127.0.0.1" or remoteaddr.split(":")[0] in "localhost":

        print(remoteaddr)
        postdata = request.POST
        print(postdata)
        # print(postdata.get("id"))
        types = postdata.get("types")
        if types == "initenv":
            initenvobj = models.initenv.objects.filter(id=postdata.get("id"))
            hostinfos = initenvobj.values("network_ip", "username","password","port").first()
            scriptobj = models.Scripts.objects.filter(id=initenvobj.get().scripts_id).get()
            scriptgpobj = scriptobj.scriptsgroup
            create_screen_cmd = "bash {}".format(os.path.join(scriptgpobj.path, scriptobj.qpname))

            ececObj = remote_exec.Remote_Exec(hostinfos.get("network_ip"), int(hostinfos.get("port")),
                                              hostinfos.get("username"),
                                              hostinfos.get("password"), create_screen_cmd, "shell")
            results = ececObj.autorun(1, 0, scriptobj.context)
            print("results:", results)
            hostinfos["screenid"] = results[0].get(hostinfos.get("network_ip")).get("screenuuid")


        elif types == "asset":
            # hostinfos = models.AssetInfo.objects.filter(hostname=postdata.get("hostname"),
            #                                             network_ip=postdata.get("network_ip")).values("network_ip",
            #                                                                                           "user__username",
            #                                                                                           "user__password",
            #                                                                                           "port").annotate(
            #    username=F('user__username') ).first()
            hostinfos = models.AssetInfo.objects.filter(hostname=postdata.get("hostname"),
                                                        network_ip=postdata.get("network_ip")).annotate(
               username=F('user__username'),password=F('user__password')).values("network_ip", "username","password","port").first()
        else:
            return JsonResponse({"code": -1})

        print(hostinfos)
        return JsonResponse({"status": 0,"data":hostinfos})
    else:
        return JsonResponse({"code": -1})


def api_hosts_check_online(request):
    postdata=request.POST.get("data")
    print(postdata)
    # [{'192.168.5.49': {'message': True, 'code': 0,
    #                    'results': {'message': '', 'code': 0, 'shell_run_time': 0.020946502685546875}}}]
    try:
        postdata=json.loads(postdata)
        from utils.remote_exec_cmd import shellcmds

        results= shellcmds.use_user_pass(postdata.get("network_ip").strip(" "), int(postdata.get("port").strip(" ")), postdata.get("username").strip(" "),
                                         postdata.get("password").strip(" "),"touch /root/.check_online && rm -f /root/.check_online")
        print(results)

    except Exception as e:
        return  JsonResponse({"code": -1,"message":str(e)})

    if len(results) ==1:
            results=results[0].get(postdata.get("network_ip").strip(" "))
            print(results)
            if  results.get("code") == 0 and results.get("message") ==True:
                return JsonResponse({"code": 0})
            return JsonResponse({"code": -1, "message": str(results.get("message"))})
    else:
        return JsonResponse({"code": -1, "message": "Failed"})
